package com.hedl.elasticsearch.elastic;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.ExistsRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.hedl.elasticsearch.service.impl.ElasticsearchServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author Big Watermelon
 * @date 2023/10/30/22:38
 */
@SpringBootTest
public class ElasticsearchTestIndex {

    public final String ELASTIC_NAME = "watermelon";

    @Resource
    private ElasticsearchServiceImpl elasticsearchService;

    @Resource
    private ElasticsearchClient elasticsearchClient;

    //这个方法执行有问题
    @Test
    public void operationIndex() throws IOException {
        //判断索引是否存在
        ExistsRequest existsRequest = new ExistsRequest.Builder().index("Windows10").build();
        BooleanResponse exists = elasticsearchClient.exists(existsRequest);

        if (exists.value()){
            System.out.println("索引："+"Windows10"+"已经存在！");
        }else {

            //需要采用构建器方式来构建对象ESAPI的对象基本上都是采用这种方式
            CreateIndexRequest indexRequest = new CreateIndexRequest.Builder().index("Windows10").build();
            CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(indexRequest);
            System.out.println("创建索引的响应对象:"+createIndexResponse);
        }
    }

    @Test
    public void operationIndex1() throws IOException {
        //判断索引，在创建索引
        boolean flg = elasticsearchClient.indices().exists(e -> e.index("windows10")).value();
        if (flg){
            System.out.println("索引："+"Windows10"+"已经存在！");
        }else {
            CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(e -> e.index("windows10"));
            System.out.println(createIndexResponse);
        }
    }

    @Test
    public void getIndex() throws IOException {
        //查询索引
        GetIndexResponse windows10 = elasticsearchClient.indices().get(x -> x.index("windows10"));
        System.out.println("查询的响应结果:"+windows10);
        System.out.println("查询的响应结果windows10:"+windows10.get("windows10"));
        System.out.println("查询的响应结果mappings:"+windows10.get("windows10").mappings());
    }

    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexResponse windows10 = elasticsearchClient.indices().delete(x -> x.index("windows10"));
        System.out.println("查看删除返回信息："+windows10);
    }
}
